const path = require('path');
const fs = require('fs');
const tools = require('./common');
const shortid = require('shortid');
const { URL } = require('url');
const jwt = require('jsonwebtoken');
const rp = require('request-promise');

const libre = require('libreoffice-convert');
libre.convertAsync = require('util').promisify(libre.convert);

/**
 * 通过本地安装的libreoffice把word,excel文件转pdf
 * @param {string} filePath 源文件地址
 * @returns 转为pdf后的路径 url
 */
async function convertByLibreoffice (filePath) {
  if (!filePath) return '';

  const rootFolder = process.env.NODE_ENV === 'development' ? path.join(path.resolve(__dirname, '../..')) : path.join(path.resolve(__dirname, '..'));
  const inputPath = path.join(rootFolder, filePath);

  if (!fs.existsSync(inputPath)) return '';

  const ext = '.pdf'
  const outputPath = path.join(rootFolder, 'uploads/output', `${path.basename(inputPath)}${ext}`);

  // Read file
  const officeBuf = fs.readFileSync(inputPath);

  // Convert it to pdf format with undefined filter (see Libreoffice docs about filter)
  const pdfBuf = await libre.convertAsync(officeBuf, ext, undefined);

  // Here in done you have pdf file which you can save or transfer in another stream
  fs.writeFileSync(outputPath, pdfBuf);

  return `${filePath}${ext}`;
}

/**
 * 通过网络部署的onlyoffice把word,excel转成pdf
 * @param {*} filePath 源文件地址
 * @returns 转为pdf后的路径 url
 */
async function convertByOnlyoffice (filePath) {
  let pdfFile = '';
  const config = await tools.getSystemConfig('onlyoffice');
  if (config) {
    let payload = {
      async: false,
      filetype: path.extname(filePath).slice(1).toLowerCase(),
      key: shortid.generate(),
      outputtype: 'pdf',
      // title: path.basename,
      url: new URL(filePath, global.domainHost).href
    }

    if (config.jwt_enabled === 'yes') {
      const token = jwt.sign(payload, config.jwt_key, { algorithm: 'HS256', expiresIn: '5m' });
      payload = { token }
    }

    const convertUrl = new URL('ConvertService.ashx', config.domain).href;

    // console.log(convertUrl, payload);
    const data = await rp({
      method: 'POST',
      uri: convertUrl,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json;charset=UTF-8'
      },
      body: payload,
      json: true
    });

    /* 返回数据包
      {
      "fileUrl": "http://jh.t3y.top:8123/cache/files/data/conv_Khirz6zTPdfd7_pdf/output.pdf/output.pdf?md5=79n66RTxKSNYtbJN3d7npQ&expires=1676082257&filename=output.pdf",
      "fileType": "pdf",
      "percent": 100,
      "endConvert": true
      } */
    // console.log(data);
    if (data.endConvert) {
      pdfFile = await tools.downloadFromUrl(data.fileUrl, `uploads/output/${path.basename(filePath)}.pdf`);
      // pdfFile = data.fileUrl;
    } else {
      console.log('convert to pdf occure error:', data, payload);
    }
  }
  return pdfFile;
}

/**
 * word,excel文件转pdf
 * @param {string} filePath 源文件地址，url
 * @param {string} mode 转换模式 libreoffice-本地的libreoffice，事先本地安装好 onlyoffice-网络的onlyoffice，远程部署好，数据库有关于onlyoffice的配置
 * @returns 转为pdf后的路径 url
 */
async function convert (filePath, mode = 'libreoffice') {
  if (mode === 'onlyoffice') {
    return await convertByOnlyoffice(filePath);
  } else {
    return await convertByLibreoffice(filePath);
  }
}

exports.convertToPdf = convert;
